import os.path

from django import forms
from django.conf import settings
from django.shortcuts import render, HttpResponse, redirect

from app01 import models
from app01.utils.bootstrap import BootStrapForm


def upload_list(request):
    if request.method == 'GET':
        return render(request, 'upload_list.html')

    # print(request.POST) # 请求体中数据
    # # {'avatar': [<InMemoryUploadedFile: 02.jpg (image/jpeg)>]}
    # print(request.FILES) # 请求发过来的文件

    file_object = request.FILES.get('avatar')
    # print(file_object.name)

    f = open(file_object.name, mode='wb')
    for chunk in file_object.chunks():
        f.write(chunk)
    f.close()

    return HttpResponse('...')


class UploadForm(BootStrapForm):
    bootstrap_exclude_fields = ['img']

    name = forms.CharField(label='姓名')
    age = forms.IntegerField(label='年龄')
    img = forms.FileField(label='头像')


def upload_form(request):
    title = 'Form上传'
    if request.method == 'GET':
        form = UploadForm()
        return render(request, 'upload_form.html', {'form': form, 'title': title})

    # 表单的数据放到data，文件数据放到files
    form = UploadForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        # {'name': '深海', 'age': 123, 'img': <InMemoryUploadedFile: 1.jpg (image/jpeg)>}
        # print(form.cleaned_data)
        # 1.读取图片内容，写入到文件夹中并获取文件的路径
        image_object = form.cleaned_data.get('img')
        # file_path = 'app01/static/img/{}'.format(image_object.name)
        # db_file_path = os.path.join('static','img', image_object.name)
        # 绝对路径
        # db_file_path = os.path.join(settings.MEDIA_ROOT, image_object.name)
        # 相对路径
        file_path = os.path.join('media', image_object.name)
        f = open(file_path, mode='wb')
        for chunk in image_object.chunks():
            f.write(chunk)
        f.close()

        # 2.将图片文件路径写入到数据库
        models.Boss.objects.create(
            name=form.cleaned_data['name'],
            age=form.cleaned_data['age'],
            img=file_path,
        )

        return HttpResponse('...')
    return render(request, 'upload_form.html', {'form': form, 'title': title})

from django import forms
from app01.utils.bootstrap import BootStrapModelForm
class UploadModelForm(BootStrapModelForm):
    bootstrap_exclude_fields = ['img']
    class Meta:
        model = models.City
        fields = '__all__'


def upload_model_form(request):
    """上传文件和数据（ModelForm）"""
    title = '新建城市'
    if request.method == 'GET':
        form = UploadModelForm()
        return render(request, 'upload_modelform.html',{'form':form, 'title':title})

    form = UploadModelForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        # 对于文件：自动保存
        # 字段 + 上传路径写入到数据库
        form.save()
        return redirect('/city/list')
    return render(request, 'upload_modelform.html',{'form':form, 'title':title})


def city_list(request):
    queryset = models.City.objects.all()
    return render(request, 'city_list.html', {'queryset':queryset})